<template>
  <div id="app">
    <Header :title="title"></Header>
    <!--表单-->
    <van-form @submit="onSubmit">
      <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button square block type="primary" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import Header from '../components/Header'
import {Dialog} from "vant";
import {Bus} from '../bus';
import {loginUser} from "../utils/api";
import {mapMutations} from 'vuex';

export default {
  name: "Login",
  components:{
    Header
  },
  data(){
    return {
      title: '登录',
      username: '',
      password: '',
      status: false
    }
  },
  methods: {
    /**
     * vuex 修改 全局状态数据
     */
    ...mapMutations(['set_userInfo','SET_Login']),
    /**
     * 登录
     * @param values 用户名 密码
     */
    onSubmit: async function (values) {
      const res= await loginUser(values.username, values.password)
      console.log(res)

      // 1.登陆成功 前往 writer 页面
      if (res.code === 100) {
        // 2.保存用户信息到全局状态 vuex
        const userInfo = {username: res.data.username, id: res.data.id, url: res.data.url}
        // 3.设置 是否登陆成功
        this.SET_Login(true);

        // 4.设置用户信息
        this.set_userInfo(userInfo);
        // 5. 同时改变 App.vue 的登录状态
        Bus.$emit('change-nav', true)
        // 6.跳转到主页面
        await this.$router.replace('/writer')
      } else {
        // 6.登陆失败，提示错误信息
        return this.fail(res.message)
      }


    },
    success(){
      Dialog.alert({
        title: '消息',
        message: '登陆成功',
        theme: 'round-button',
      }).then(() => {
        // on close
      });
    },
    fail(message){
      Dialog.alert({
        title: '消息',
        message: message,
        theme: 'round-button',
      }).then(() => {
        // on close
      });
    },
  },
}
</script>

<style scoped>

</style>